package com.bruce.springbootDemo.config;

import com.bruce.springbootDemo.web.restFul.ResponseEntity;
import com.bruce.springbootDemo.web.restFul.ResponseTool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * Created by bruce on 18/11/22 -- 16:02
 */
@ControllerAdvice
public class GlobalExceptionHandler {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 全局异常捕捉处理
     *
     * @param ex
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public ResponseEntity errorHandler(Exception ex) {
        logger.error("异常捕获：" + getExceptionAllinformation(ex));
        return ResponseTool.fail(400, ex.getMessage());
    }

    private String getExceptionAllinformation(Exception ex) {
        String sOut = "";
        StackTraceElement[] trace = ex.getStackTrace();
        for (StackTraceElement s : trace) {
            sOut += "\tat " + s + "\r\n";
            break;
        }
        return sOut;
    }
}
